package com.smzd.framework.system.business;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.smzd.core.dao.IDao;
import com.smzd.core.domain.Many2Many;
import com.smzd.framework.core.business.AbstractFGService;
import com.smzd.framework.system.dao.ModuleDao;
import com.smzd.framework.system.domain.Module;
import com.smzd.framework.utils.db.FGRowConverter;
import com.smzd.framework.utils.db.RPage;
import com.smzd.utils.SimpleDateTimeUtil;

@Service
public class ModuleService extends AbstractFGService<Module> {
	@Autowired
	private ModuleDao dao;

	@Override
	protected IDao<Module> getDao() {
		return dao;
	}

	@Override
	public FGRowConverter<Module> getConverter() {
		return ModuleService.converter;
	}

	private static FGRowConverter<Module> converter = new FGRowConverter<Module>() {
		@Override
		public Object[] convert(Module elem) {
			Date pubDate = elem.getPubDate();
			String pubDateStr = SimpleDateTimeUtil.formatToDate(pubDate);
			Date installDate = elem.getInstallDate();
			String installDateStr = SimpleDateTimeUtil.formatToDate(installDate);
			Object[] fields = new Object[] { 
					elem.getId(), 
					elem.getName(),
					elem.getAuthor(),
					pubDateStr,
					installDateStr,
					elem.getDescription()
			};
			return fields;
		}
	};
	private static FGRowConverter<Module> checkedConverter = new FGRowConverter<Module>() {
		@Override
		public Object[] convert(Module elem) {
			Object[] fields = new Object[] { 
					elem.getId(), 
					elem.getName(),
					elem.getDescription(),
					elem.getChecked()
			};
			return fields;
		}
	};

	public String getMeetingGroupsListDataJson(RPage<Module> page) {
		dao.getMeetingModuleListByPage(page);
		return page.toFlexiGridJsonString(checkedConverter);
	}

	public void saveMeetingModules(int meetingId, String moduleIds) {
		String[] ids = moduleIds.split(",");
		List<Many2Many> toAdd = new ArrayList<Many2Many>();
		List<Many2Many> toDel = new ArrayList<Many2Many>();
		for(String id : ids){
			int rid = Integer.parseInt(id);
			Many2Many mm = new Many2Many();
			mm.setKey1(meetingId);
			if(rid<0){
				mm.setKey2(-rid);
				toDel.add(mm);
			}else{
				mm.setKey2(rid);
				toAdd.add(mm);
			}
		}
		dao.saveMeetingModules(toAdd, toDel);
	}
}
